package com.atguigu.yygh.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.exception.YyghException;
import com.atguigu.yygh.mapper.ScheduleMapper;
import com.atguigu.yygh.model.hosp.BookingRule;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.repository.ScheduleRepository;
import com.atguigu.yygh.result.ResultCodeEnum;
import com.atguigu.yygh.service.DepartmentService;
import com.atguigu.yygh.service.HospitalService;
import com.atguigu.yygh.service.ScheduleService;
import com.atguigu.yygh.vo.hosp.BookingScheduleRuleVo;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.atguigu.yygh.vo.hosp.ScheduleQueryVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.*;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zr
 * @date 2021/12/13 16:23
 */
@Service
public class ScheduleServiceImpl extends ServiceImpl<ScheduleMapper, Schedule> implements ScheduleService {
    @Resource
    private ScheduleRepository scheduleRepository;
    @Resource
    private MongoTemplate mongoTemplate;
    @Resource
    private HospitalService hospitalService;
    @Resource
    private DepartmentService departmentService;

    @Override
    public void saveSchedule(Map<String, Object> paramMap) {
        // 将paramMap转化为对象
        String resultMap = JSONObject.toJSONString(paramMap);
        Schedule schedule = JSONObject.parseObject(resultMap, Schedule.class);
        // 根据医院编号 和排班编号进行查询
        Schedule scheduleExists = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());
        if (scheduleExists != null) {
            BeanUtils.copyProperties(schedule, scheduleExists);
            scheduleRepository.save(scheduleExists);
        }
        // 保存
        schedule.setCreateTime(new Date());
        schedule.setUpdateTime(new Date());
        schedule.setIsDeleted(0);
        scheduleRepository.save(schedule);
    }

    @Override
    public Page<Schedule> findPageSchedule(Integer page, Integer limit, ScheduleQueryVo scheduleQueryVo) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(page - 1, limit, sort);
        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(scheduleQueryVo, schedule);
        schedule.setIsDeleted(0);
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.STARTING)
                .withIgnoreCase(true);
        Example<Schedule> example = Example.of(schedule, exampleMatcher);
        Page<Schedule> all = scheduleRepository.findAll(example, pageable);
        return all;
    }

    @Override
    public void removeSchedule(String hosCode, String hosScheduleId) {
        Schedule schedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hosCode, hosScheduleId);
        if (schedule != null) {
            scheduleRepository.deleteById(schedule.getId());
        }
    }

    /**
     * 根据医院编号 和科室编号 查询排班规则
     *
     * @param page
     * @param limit
     * @param hosCode
     * @param depCode
     * @return
     */
    @Override
    public Map<String, Object> getScheduleRule(long page, long limit, String hosCode, String depCode) {
        // 根据医院编号 和科室编号查询  写出条件
        Criteria criteria = Criteria.where("hoscode").is(hosCode).and("depcode").is(depCode);
        // 进行聚合操作 根据工作日期 workDate 进行分组
        Aggregation aggregation = Aggregation.newAggregation(
                // 匹配条件
                Aggregation.match(criteria),
                // 分组
                Aggregation.group("workDate")
                        // 取别名并取值
                        .first("workDate").as("workDate")
                        // 统计号源数量
                        .count().as("docCount")
                        // 可预约数求和
                        .sum("reservedNumber").as("reservedNumber")
                        // 剩余预约数求和
                        .sum("availableNumber").as("availableNumber"),
                // 按照workDate进行排序
                Aggregation.sort(Sort.Direction.ASC, "workDate"),
                // 实现分页操作
                Aggregation.skip((page - 1) * limit),
                Aggregation.limit(limit)
        );
        // 调用方法最终实现
        AggregationResults<BookingScheduleRuleVo> aggregationResults = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        // 得到最终返回结果
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggregationResults.getMappedResults();
        // 封装数据 TOOD
        // 获取分组查询的总记录数
        Aggregation totalAggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );
        AggregationResults<BookingScheduleRuleVo> totalAggResults = mongoTemplate.aggregate(totalAggregation, Schedule.class, BookingScheduleRuleVo.class);
        // 获取记录数 也就是list的size
        int total = totalAggResults.getMappedResults().size();
        // 获取日期对应的星期
        for (BookingScheduleRuleVo bookingScheduleRuleVo : bookingScheduleRuleVoList) {
            // 获取日期
            Date workDate = bookingScheduleRuleVo.getWorkDate();
            // 根据日期获取星期
            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
            // 设置日期
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        }
        // 设置最终数据 进行返回
        Map<String, Object> result = new HashMap<>();
        result.put("bookingScheduleRuleList", bookingScheduleRuleVoList);
        result.put("total", total);
        // 设置医院名称
        Hospital hospitalByHosCode = hospitalService.getHospitalByHosCode(hosCode);
        String hosName = "";
        if (hospitalByHosCode != null) {
            hosName = hospitalByHosCode.getHosname();
        }
        Map<String, Object> baseMap = new HashMap<>();
        baseMap.put("hosName", hosName);
        result.put("baseMap", baseMap);
        return result;
    }

    /**
     * 根据医院编号 和科室编号、工作日期 查询排班详情
     *
     * @param hosCode
     * @param depCode
     * @param workDate
     * @return
     */
    @Override
    public List<Schedule> getScheduleDetail(String hosCode, String depCode, String workDate) {
        // 解决时间为空 报错的bug
        // 根据参数查询MongoDB
        List<Schedule> scheduleList = scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate(hosCode, depCode, workDate == null ? new Date() : new DateTime(workDate).toDate());
        // 遍历集合 向里面设置数据
        scheduleList.stream().forEach(schedule -> {
            this.packageSchedule(schedule);
        });
        return scheduleList;
    }

    /**
     * 获取可预约排班数据
     *
     * @param page
     * @param limit
     * @param hosCode
     * @param depCode
     * @return
     */
    @Override
    public Map<String, Object> getBookingScheduleRule(Integer page, Integer limit, String hosCode, String depCode) {
        Map<String, Object> result = new HashMap<>();
        // 获取预约规则
        Hospital hospital = hospitalService.getHospitalByHosCode(hosCode);
        if (hospital == null) {
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }
        BookingRule bookingRule = hospital.getBookingRule();
        // 获取分页的可预约日期数据
        IPage listPage = this.getListPage(page, limit, bookingRule);
        List<Date> dateList = listPage.getRecords();
        // 根据医院编号 科室编号 获取可预约日期科室剩余预约数
        Criteria criteria = Criteria.where("hoscode")
                .is(hosCode).and("depcode")
                .is(depCode).and("workDate").in(dateList);
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                // 分组
                Aggregation.group("workDate")
                        .first("workDate").as("workDate")
                        // 计算医生人数
                        .count().as("docCount")
                        .sum("availableNumber").as("availableNumber")
                        .sum("reservedNumber").as("reservedNumber")
        );
        // 获取科室的剩余预约数
        AggregationResults<BookingScheduleRuleVo> scheduleRuleVos = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> scheduleVoList = scheduleRuleVos.getMappedResults();
        // 合并最终的数据 将统计数据ScheduleVO根据安排日期合并到BookingScheduleRuleVo
        // 创建Map集合 key作为日期 value作为BookingScheduleRuleVo
        Map<Date, BookingScheduleRuleVo> scheduleRuleVoMap = new HashMap<>();
        // 如果scheduleVoList不为空 使用聚合操作 将scheduleVoList集合转为scheduleRuleVoMap
        if (!CollectionUtils.isEmpty(scheduleVoList)) {
            scheduleRuleVoMap = scheduleVoList
                    .stream()
                    .collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate,
                            BookingScheduleRuleVo -> BookingScheduleRuleVo));
        }
        // 获取可预约的排班规则
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        for (int i = 0, len = dateList.size(); i < len; i++) {
            Date date = dateList.get(i);
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleRuleVoMap.get(date);
            // 判断bookingScheduleRuleVo是否为空 为空则代表 当天没有医生
            if (bookingScheduleRuleVo == null) {
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                // 设置医生人数为0
                bookingScheduleRuleVo.setDocCount(0);
                // 科室剩余预约数  -1表示无号
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }
            // 设置可预约日期
            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);
            // 计算当前预约日期 为周几
            String dayOfWeek = this.getDayOfWeek(new DateTime(date));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
            // 如果是最后一页 最后一条记录 则是即将放号 0代表正常 1代表即将放号 -1代表停止放号
            if (i == len - 1 && page == listPage.getPages()) {
                bookingScheduleRuleVo.setStatus(1);
            } else {
                bookingScheduleRuleVo.setStatus(0);
            }
            // 如果当天预约如果过了停号时间 则不能预约
            if (i == 0 && page == 1) {
                // 获取停号时间
                DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
                if (stopTime.isBeforeNow()) {
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }
            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
            // 可预约日期规则数据
            result.put("bookingScheduleList", bookingScheduleRuleVoList);
            result.put("total", listPage.getTotal());
            // 其他基础数据
            Map<String, Object> baseMap = new HashMap<>();
            // 获取医院名称
            baseMap.put("hosname", hospital.getHosname());
            // 获取科室
            Department department = departmentService.getDepartment(hosCode, depCode);
            // 获取大科室 及小科室
            //大科室名称
            baseMap.put("bigname", department.getBigname());
            //科室名称
            baseMap.put("depname", department.getDepname());
            //月
            baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
            //放号时间
            baseMap.put("releaseTime", bookingRule.getReleaseTime());
            //停号时间
            baseMap.put("stopTime", bookingRule.getStopTime());
            result.put("baseMap", baseMap);
        }
        return result;
    }

    /**
     * 根据排班id获取排班数据
     *
     * @param scheduleId
     * @return
     */
    @Override
    public Schedule getSchedule(String scheduleId) {
        Schedule schedule = scheduleRepository.findById(scheduleId).get();
        return this.packageSchedule(schedule);
    }

    /**
     * 根据排班id获取预约下单数据
     *
     * @param scheduleId
     * @return
     */
    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        // 获取排班信息
        Schedule schedule = scheduleRepository.findById(scheduleId).get();
        // 获取预约规则信息
        Hospital hospital = hospitalService.getHospitalByHosCode(schedule.getHoscode());
        if (hospital == null) {
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }
        BookingRule bookingRule = hospital.getBookingRule();
        if (bookingRule == null) {
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }
        // 向scheduleOrderVo里设置数据
        scheduleOrderVo.setHoscode(schedule.getHoscode());
        // 设置医院名
        scheduleOrderVo.setHosname(hospital.getHosname());
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        scheduleOrderVo.setDepname(departmentService.getDepName(schedule.getHoscode(), schedule.getDepcode()));
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        scheduleOrderVo.setTitle(schedule.getTitle());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        scheduleOrderVo.setAmount(schedule.getAmount());
        // 退号截止天数 (就诊前一天为-1 当天为0)
        Integer quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());
        //预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

        //预约截止时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());

        //当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStopTime(stopTime.toDate());
        return scheduleOrderVo;
    }

    /**
     * 修改排班
     *
     * @param schedule
     */
    @Override
    public void update(Schedule schedule) {
        schedule.setUpdateTime(new Date());
        scheduleRepository.save(schedule);
    }

    /**
     * 获取可预约日期 分页数据
     */
    private IPage getListPage(Integer page, Integer limit, BookingRule bookingRule) {
        // 获取当天的放号时间
        DateTime releaseTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        // 获取预约周期
        Integer cycle = bookingRule.getCycle();
        // 如果当天的放号时间 已过 周期就要加1 放号时间推迟
        if (releaseTime.isBeforeNow()) {
            cycle += 1;
        }
        // 显示 所有的可预约日期 最后一天显示即将放号倒计时
        List<Date> dateList = new ArrayList<>();
        for (int i = 0; i < cycle; i++) {
            // 计算当前的预约日期
            DateTime curDateTime = new DateTime().plusDays(i);
            String curDateString = curDateTime.toString("yyyy-MM-dd");
            dateList.add(new DateTime(curDateString).toDate());
        }
        // 日期分页显示  由于日期周期不一样 页面一排最多显示7天的数据
        List<Date> pageDateList = new ArrayList<>();
        int start = (page - 1) * limit;
        int end = (page - 1) * limit + limit;
        // 判断末尾是否大于总共的日期数
        if (end > dateList.size()) {
            end = dateList.size();
        }
        for (int i = start; i < end; i++) {
            pageDateList.add(dateList.get(i));
        }
        IPage<Date> iPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page(page, 7, dateList.size());
        iPage.setRecords(pageDateList);
        return iPage;
    }

    /**
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     */
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " " + timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }

    /**
     * 封装排班详情其他值 医院名称、科室名称、日期对应星期
     *
     * @param schedule
     */
    private Schedule packageSchedule(Schedule schedule) {
        Hospital hospital = hospitalService.getHospitalByHosCode(schedule.getHoscode());
        // 设置医院名称
        schedule.getParam().put("hosname", hospital == null ? "" : hospital.getHosname());
        // 设置科室名称
        schedule.getParam().put("depname", departmentService.getDepName(schedule.getHoscode(), schedule.getDepcode()));
        schedule.getParam().put("dayOfWeek", this.getDayOfWeek(new DateTime(schedule.getWorkDate())));
        // 返回schedule
        return schedule;
    }

    /**
     * 根据日期获取周几数据
     *
     * @param dateTime
     * @return
     */
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }

}
